package com.blog.controller;

import com.blog.entity.Article;
import com.blog.entity.Comment;
import com.blog.entity.User;
import com.blog.mapper.ArticleMapper;
import com.blog.mapper.CommentMapper;
import com.blog.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/stats")
public class StatsController {

    @Autowired
    private ArticleMapper articleMapper;
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private CommentMapper commentMapper;
    
    @GetMapping
    public ResponseEntity<Map<String, Object>> getSiteStats() {
        // 获取文章总数
        Long articleCount = articleMapper.selectCount(null);
        
        // 获取总访问量
        Long viewCount = articleMapper.selectViewCount();
        
        // 获取评论总数
        Long commentCount = commentMapper.selectCount(null);
        
        // 获取用户总数
        Long userCount = userMapper.selectCount(null);
        
        // 计算网站运行天数（以第一个用户注册时间为起点）
        User firstUser = userMapper.selectFirstUser();
        long dayCount = 0;
        if (firstUser != null && firstUser.getCreateTime() != null) {
            LocalDateTime startDate = firstUser.getCreateTime();
            dayCount = ChronoUnit.DAYS.between(startDate.toLocalDate(), LocalDate.now());
        }
        
        Map<String, Object> stats = new HashMap<>();
        stats.put("articleCount", articleCount);
        stats.put("viewCount", viewCount);
        stats.put("commentCount", commentCount);
        stats.put("userCount", userCount);
        stats.put("dayCount", dayCount);
        
        return ResponseEntity.ok(stats);
    }
} 